package org.gjy.m8.thread;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;
import java.util.concurrent.*;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-08-17 14:22:46
 */
public class CompletableFutureTest {

    private static final Logger log = LoggerFactory.getLogger(CompletableFutureTest.class);

    private static final int processor = Runtime.getRuntime().availableProcessors();

    @Test
    public void test5() {
        CompletableFuture<Void> run = CompletableFuture.supplyAsync(() -> {
            String s = UUID.randomUUID().toString();
            log.info("查询数据: {}", s);
            return s;
        }).thenApply(s -> {
            log.info("处理前: {}", s);
            String nS = s.replaceAll("-", "");
            log.info("处理后: {}", nS);
            return nS;
        }).thenRun(() -> log.info("重新写入完成"));

        run.join();
    }

    @Test
    public void test4() throws InterruptedException {
        CompletableFuture.supplyAsync(UUID::randomUUID)
                .thenApply(a -> a.toString().replaceAll("-", ""))
                .thenAccept(a -> log.info("{}", a));
        TimeUnit.SECONDS.sleep(1);
    }

    @Test
    public void test3() {
        CompletableFuture<UUID> async = CompletableFuture.supplyAsync(UUID::randomUUID);

        UUID join = async.join();

        System.out.println(join);
    }

    @Test
    public void test2() throws InterruptedException {
        CountDownLatch cdl = new CountDownLatch(1);
        ExecutorService pool = Executors.newFixedThreadPool(1);

        ForkJoinPool joinPool = new ForkJoinPool(
                processor
        );

        CompletableFuture.runAsync(() -> {
            log.info("Hello");
            cdl.countDown();
        }, joinPool);

        cdl.await();
    }

    @Test
    public void test1() throws Exception {
        CompletableFuture<String> async = CompletableFuture.supplyAsync(() -> {
            return UUID.randomUUID().toString();
        });

        System.out.println("async.get() = " + async.get());
    }

}
